package com.zd.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

// 反射？
public class Client03 {

    public static void main(String[] args) throws IOException {

        // 客户端连接服务器 根据ip或域名和端口号
        Socket socket =
                new Socket("localhost" , 8888);
        System.out.println("客户端根据ip或域名和端口连接服务器成功!");

        ClientThread clientThread = new ClientThread(socket);
        clientThread.start();

        // PrintStream 打印功能的输出流 注意 底层是socket 网络输出流 字节流
        PrintStream printStream =
                new PrintStream(socket.getOutputStream());

        // 对于客户端 要读取键盘 System.in（随时）输入的数据，发送给服务器
        BufferedReader bufferedReaderSystemIn =
                new BufferedReader(new InputStreamReader(System.in));

        String lineSystemIn = null;

        // 如果读取到键盘数据 就给服务器发送 否则一直读  线程阻塞问题
        while( (lineSystemIn = bufferedReaderSystemIn.readLine()) != null ){
            System.out.println("客户端收到的键盘输入的数据: " + lineSystemIn + " , 马上给服务器发过去!");

            printStream.println(lineSystemIn);
            printStream.flush(); // 刷新缓冲区
        }


    }
}

class ClientThread extends Thread {

    private Socket socket;

    public ClientThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {

        // 客户端读取服务器任意时刻发送过来的数据
        BufferedReader bufferedReader =
                null;
        try {
            bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            String line = null;

            // 如果读取到服务器的数据 就给打印到控制台 否则一直读  线程阻塞问题
            while( (line = bufferedReader.readLine()) != null){

                System.out.println("客户端收到的服务器发送回来的数据: " + line );
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }



    }
}